package com.example.weight.wormHandle.cultivate;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class fenhe extends AppCompatActivity {

    final DecimalFormat formater = new DecimalFormat();

    private MiddleWormBox selectBox;

    private String name,fenhe_belongTo_id,fenhe_Text, factory;

    private TextView batch_text, tv_begin_date;
    private EditText et_total_weight, et_net_weight, et_per_box,et_box_quality;
    //    , et_per_box_material;
//    private EditText start_number;
    private String activeButton;

    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    @SuppressLint("SimpleDateFormat")
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fenhe);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        selectBox = (MiddleWormBox) previousIntent.getSerializableExtra("selectBox");
//        fenhe_belongTo_id = previousIntent.getStringExtra("fenhe_belongTo_id");
//        fenhe_Text = previousIntent.getStringExtra("fenhe_Text");
//        Toast.makeText(this, "fenhe_belongTo_id:"+fenhe_belongTo_id, Toast.LENGTH_SHORT).show();

//        RequestQueue queue = Volley.newRequestQueue(this);
//        String url1 = Config.url + "/hsmpy/middleWormBreedingFeed/getlist?id=" + selectBox.getId();
//        StringRequest stringRequest1 = new StringRequest(Request.Method.GET, url1,
//                new Response.Listener<String>() {
//                    @Override
//                    public void onResponse(String response) {
//                        try {
//                            JSONObject jsonObject = new JSONObject(response);
//                            if (!jsonObject.isNull("data")) {
//                                JSONArray data = jsonObject.getJSONArray("data");
//                                if( data.length()>0){
//                                    for (int i=0; i < data.length(); i++){
//                                        JSONObject record = data.getJSONObject(i);
//                                        selectBox.setSmallBoxWeight(record.getDouble("smallBugBoxMaterialWeight"));
//                                        selectBox.setBoxQuality(record.getInt("number"));
//                                    }
//                                }
//                            }
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }, new Response.ErrorListener() {
//            @Override
//            public void onErrorResponse(VolleyError error) {
//                Toast.makeText(fenhe.this,
//                        "获取待分盒信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
//            }
//        });
//        stringRequest1.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
//                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//        queue.add(stringRequest1);

        formater.setMaximumFractionDigits(4);
        formater.setGroupingSize(0);
        formater.setRoundingMode(RoundingMode.FLOOR);

        TitleBar titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                fenhe.this.finish();
            }
            @Override
            public void onTitleClick(View v) { }
            @Override
            public void onRightClick(View v) { }
        });

        batch_text = findViewById(R.id.batch_text);
        et_box_quality = findViewById(R.id.et_box_quality);
        et_total_weight = findViewById(R.id.et_total_weight);
        et_net_weight = findViewById(R.id.et_net_weight);
        et_per_box = findViewById(R.id.et_per_box);
//        et_per_box_material = findViewById(R.id.et_per_box_material);

        tv_begin_date = findViewById(R.id.tv_begin_date);

        batch_text.setText(selectBox.toString());

        et_total_weight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(selectBox.getSmallBoxWeight() == null){
                    Toast.makeText(fenhe.this, "请检查数据库小虫培育盒重异常", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(et_total_weight.getText().toString().equals("")){
                    return;
                }
                Double netWeight = Double.parseDouble(et_total_weight.getText().toString())-selectBox.getSmallBoxWeight();
                et_net_weight.setText(formater.format(netWeight));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        et_box_quality.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if(et_net_weight.getText().toString().equals("")){
                    Toast.makeText(fenhe.this, "请先输入总重", Toast.LENGTH_SHORT).show();
                    return;
                }
                Double perBox = Double.parseDouble(et_net_weight.getText().toString()) / Integer.parseInt(et_box_quality.getText().toString());
                et_per_box.setText(formater.format(perBox));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        tv_begin_date.setText(simpleDateFormat.format(new Date()));
        tv_begin_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(fenhe.this, 2, tv_begin_date, calendar);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
//        Log.d("refresh","fenhe");
        Intent intent = new Intent();
        intent.putExtra("needRefresh", true);
        setResult(RESULT_OK, intent);
    }

    public void save(View view) {
        if(et_box_quality.getText().toString().equals("")) {
            Toast.makeText(this, "请填写分盒数量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_total_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请获取小虫培育盒、虫和渣重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if(et_box_quality.getText().toString().equals("")) {
            Toast.makeText(this, "请填写中虫分盒数", Toast.LENGTH_SHORT).show();
            return;
        }
//        if(et_per_box_material.getText().toString().equals("")) {
//            Toast.makeText(this, "请获取中虫每盒加培育料", Toast.LENGTH_SHORT).show();
//            return;
//        }
//        if(start_number.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写分盒起始编号数字", Toast.LENGTH_SHORT).show();
//            return;
//        }
        Log.d("fenhe", selectBox.getGroup());

        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {

                    selectBox.setBeginDate(tv_begin_date.getText().toString());
                    selectBox.setBoxQuality(Integer.parseInt(et_box_quality.getText().toString()));
                    selectBox.setTotalWeight(Double.parseDouble(et_total_weight.getText().toString()));
                    selectBox.setNetWeight(Double.parseDouble(et_net_weight.getText().toString()));
                    selectBox.setPerBox(Double.parseDouble(et_per_box.getText().toString()));
//                    selectBox.setPerBoxMaterial(Double.parseDouble(et_per_box_material.getText().toString()));

//                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/hsmpy/middleWormBreedingFeed/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2")) {
                                            Toast.makeText(fenhe.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();finish();
                                        }else{
                                            Toast.makeText(fenhe.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();}
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(fenhe.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("id", selectBox.getId());
                            map.put("batch", selectBox.getBatch());
                            map.put("worm_group", selectBox.getGroup());
                            map.put("small_bug_breed_box_number", selectBox.getSmallNum());
                            map.put("big_bug_breed_start_time", tv_begin_date.getText().toString());
                            map.put("small_bug_box_material_weight", selectBox.getTotalWeight().toString());
                            map.put("small_bug_material_weight", selectBox.getNetWeight().toString());
                            map.put("number", selectBox.getBoxQuality().toString());
                            map.put("per_bug_material_weight", selectBox.getPerBox().toString());
                            map.put("big_bug_per_box_breed_material_weight", "0");
                            map.put("serial", "0");
                            map.put("go_where", "0");
                            map.put("big_bug_breed_box_number", "0");
                            map.put("big_bug_number", "0");
                            map.put("big_bug_material_target_value", "0");
                            map.put("big_bug_material_get_value", "0");
                            map.put("big_bug_breed_end_time", "0");
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();



    }

    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.btn_get_total_weight:
                activeButton = "btn_get_total_weight";
                break;
            default:
                break;
        }
        Intent intent = new Intent(fenhe.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "btn_get_total_weight":
                et_total_weight.setText(weight);
                break;
        }
    }

    public void turnBack() {
        Intent intent =new Intent(fenhe.this, BigBugBreedInNav.class);
        intent.putExtra("name", name);
        intent.putExtra("selectBox", selectBox);
        intent.putExtra("factory", factory);
        startActivityForResult(intent, 1);
    }


    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
}